package com.sw.fileServer.controller;


import com.sw.fileServer.model.FileInfo;
import com.sw.fileServer.model.ResultInfo;
import com.sw.fileServer.utils.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
public class Controller {

    /**
     * 文件服务器地址
     */
    @Value("${fileServer.hostPrefix}")
    private String hostPrefix;

    /**
     * 文件绝对路径前缀
     */
    @Value("${fileServer.absolutePathPrefix}")
    private String absolutePathPrefix;

    private final static List<String> IMG = new ArrayList<>();
    private final static List<String> DOCUMENT = new ArrayList<>();
    private final static List<String> VIDEO = new ArrayList<>();
    private final static List<String> AUDIO = new ArrayList<>();
    private final static List<String> WORD = new ArrayList<>();
    private final static List<String> EXCEL = new ArrayList<>();
    private final static List<String> PPT = new ArrayList<>();

    static {
        IMG.add(".jpg");
        IMG.add(".jpeg");
        IMG.add(".png");
        IMG.add(".bmp");
        IMG.add(".gif");
        IMG.add(".webp");

        DOCUMENT.add(".doc");
        DOCUMENT.add(".docx");
        DOCUMENT.add(".xls");
        DOCUMENT.add(".xlsx");
        DOCUMENT.add(".pdf");
        DOCUMENT.add(".ppt");
        DOCUMENT.add(".pptx");

        VIDEO.add(".mp4");

        AUDIO.add(".wave");
        AUDIO.add(".mpeg");
        AUDIO.add(".mp3");
        AUDIO.add(".wma");
        AUDIO.add(".amr");
        AUDIO.add(".flac");
        AUDIO.add(".aac");
        AUDIO.add(".wav");


        WORD.add(".doc");
        WORD.add(".docx");
        EXCEL.add(".xls");
        EXCEL.add(".xlsx");
        PPT.add(".ppt");
        PPT.add(".pptx");
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 单个文件上传
     *
     * @param file 文件
     * @param bucketName 桶名
     */
    @PostMapping("/uploadFile")
    public ResultInfo<?> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("bucketName") String bucketName) throws Exception {

        if (file.isEmpty()) {
            return ResultInfo.error("上传文件为空");
        }

        if (StringUtils.isEmpty(bucketName)) {
            return ResultInfo.error("桶名为空");
        }

        //获取原文件名
        String originalFilename = file.getOriginalFilename();

        if (StringUtils.isEmpty(originalFilename)) {
            return ResultInfo.error("原文件名为空");
        }

        //获取文件扩展名
        String ext;
        try {
            ext = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        } catch (Exception e) {
            log.info("文件扩展名为空,默认当做jpg文件");
            ext = ".jpg";
        }

        long size = file.getSize();
        String fileSize = byteUnitConversion(size);

        //生成新的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + ext;

        log.info("开始上传文件, bucketName: {}, fileName: {}, newFileName: {}, 文件大小: {}", bucketName, originalFilename, newFileName, fileSize);

        //上传文件
        String fileUrl = fileUploadUtil.uploadFile(file, bucketName, newFileName);

        //返回对象
        FileInfo fileInfo = new FileInfo();
        fileInfo.setOriginalName(originalFilename);
        fileInfo.setOriginalExt(ext);
        fileInfo.setOriginalSize(size);
        fileInfo.setFileSize(fileSize);
        if (IMG.contains(ext)) {
            fileInfo.setFileType(FileInfo.IMG);
        } else if (DOCUMENT.contains(ext)) {
            fileInfo.setFileType(FileInfo.DOCUMENT);
        } else if (VIDEO.contains(ext)) {
            //获取时长
            fileInfo.setFileType(FileInfo.VIDEO);
            //绝对路径
            MultimediaObject instance = new MultimediaObject(new File(absolutePathPrefix + bucketName + File.separator + newFileName));
            MultimediaInfo result = instance.getInfo();
            long ls = result.getDuration() / 1000;
            fileInfo.setVideoLength(ls);
        } else if (AUDIO.contains(ext)) {
            //获取时长
            fileInfo.setFileType(FileInfo.AUDIO);
            //绝对路径
            MultimediaObject instance = new MultimediaObject(new File(absolutePathPrefix + bucketName + File.separator + newFileName));
            MultimediaInfo result = instance.getInfo();
            long ls = result.getDuration() / 1000;
            fileInfo.setAudioLength(ls);
        } else {
            fileInfo.setFileType(FileInfo.OTHER);
        }
        fileInfo.setFileUrl(fileUrl);
        //pdf默认文件地址,防止不转pdf时pdf地址为空
        fileInfo.setPdfFileUrl(fileUrl);

//        //pdf文件名
//        String pdfFileName = uuid + ".pdf";
//        if (".pdf".equals(ext)) {
//            //原文件是pdf
//            fileInfo.setPdfFileUrl(fileInfo.getFileUrl());
//            //获取pdf页数
//            int pages = fileUploadUtil.getPdfInfo(bucketName, pdfFileName);
//            fileInfo.setPages(pages);
//        } else if (DOCUMENT.contains(ext)) {
//            //文档类型文件,统一转pdf
//            // 异步操作
//            String finalExt = ext;
//            new Thread(() -> {
//                try {
//                    fileUploadUtil.toPdf(bucketName, newFileName, finalExt);
//                } catch (Exception e) {
//                    log.error("转pdf失败", e);
//                    // 关闭线程
//                    Thread.currentThread().interrupt();
//                }
//            }).start();
//            fileInfo.setPdfFileUrl(hostPrefix + bucketName + File.separator + pdfFileName);
//            //获取pdf页数 前端有页数的实际需求吗 ?
////            int pages = fileUploadUtil.getPdfInfo(bucketName, pdfFileName);
////            fileInfo.setPages(pages);
//        }

        return ResultInfo.success("success", fileInfo);
    }

    /**
     * 字节单位换算
     */
    public static String byteUnitConversion(long bytes) {
        BigDecimal fileSize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = fileSize.divide(megabyte, 2, RoundingMode.UP).floatValue();
        if (returnValue > 1) {
            return returnValue + "MB";
        }
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = fileSize.divide(kilobyte, 2, RoundingMode.UP).floatValue();
        return returnValue + "KB";
    }
}
